//
//  OauthViewController.swift
//  weibo
//
//  Created by tomato on 2021/9/26.
//

import UIKit
import WebKit  // Swift 5.0之后 使用WKWebView 需要引入头文件了, 且UIWebView被废弃了
import SVProgressHUD

class OauthViewController: UIViewController{
    // MARK: 懒加载 微博的oauth授权(登录)界面
    var webView: WKWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        //加载控件
        setUpViews()
        //网页加载
        loadPage()
    }
}

// MARK: - 设置相关界面
extension OauthViewController{
    //加载相关view
    private func setUpViews(){
        view.backgroundColor = .white
        //标题
        title = "微博登录"
        //左侧item
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action:#selector(closeClick))
        //右侧item
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action:#selector(fillClick))

        //加载WKWebView
        webView = WKWebView(frame:view.bounds)
        webView.navigationDelegate = self
        // 将 WKWebView 添加到视图中
        view.addSubview(webView)
    }
    
    //网页加载
    private func loadPage(){
        if let url = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=3005221540&redirect_uri=https://www.baidu.com") {
          webView.load(URLRequest(url: url))
        }
    }
}


// MARK: - 点击事件
extension OauthViewController{
    
   @objc private func closeClick(){
       dismiss(animated: true,completion:nil)
   }
    
   @objc private func fillClick(){
//       Print(items:"填充")
   }
}

// MARK: - webview代理
extension OauthViewController:WKNavigationDelegate{
    // 页面开始加载时调用
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
//        Print(items: "didStartProvisionalNavigation")
        SVProgressHUD.show()
    }
    // 当内容开始返回时调用
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
//        Print(items: "didCommit")
    }
    // 页面加载完成之后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
//        Print(items: "didFinish")
        SVProgressHUD.dismiss()
    }
    // 页面加载失败时调用
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
//        Print(items: "didFailProvisionalNavigation")
        SVProgressHUD.dismiss()
    }
    // 在发送请求之前，决定是否跳转 -> 默认允许
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, preferences: WKWebpagePreferences, decisionHandler: @escaping (WKNavigationActionPolicy, WKWebpagePreferences) -> Void) {
        //获取加载网页的url
        guard let  url = navigationAction.request.url else{
            return
        }
        let urlString = url.absoluteString
        //判断该字符串是否包含code
        guard urlString.contains("code=") else {
            decisionHandler(.allow, preferences)//没有此句会闪退
            return
        }
        
        //将code截取出来
        let code = urlString.components(separatedBy:"code=").last!
        //请求accessToken
        loadAccessToken(code: code)
        //没有此句会闪退
        decisionHandler(.allow, preferences)
    }
}

// MARK: - 网络数据请求
extension OauthViewController{
    //请求accessToken
    private func loadAccessToken(code:String){
        NetworkAlamofireTools.sharedInstance.loadAccessToken(code: code) { (result) in
            SVProgressHUD.dismiss()
            //判断dicResult 是否为nil 而且是否为一个字典
            guard let dicResult = result as? [String: Any] else{
                //没有数据
                return
            }
            //将字典转为模型
            let account = UserAccount(dict:dicResult)
            self.getUserInfoRequest(account:account)
        } failure: { (error) in
            SVProgressHUD.dismiss()
        }
    }
    
    //请求个人信息
    private func getUserInfoRequest(account:UserAccount){
//        NetworkAlamofireTools.sharedInstance.getUserInfo(accessToken: account.access_token!, userID: account.uid!) { (resultDic) in
//            self.dismiss(animated: true)
//        } failure: { (error) in
//            self.dismiss(animated: true)
//        }
        NetworkAlamofireTools.sharedInstance.getHomeListRequest(accessToken: account.access_token!) { (resultDic) in
    
        } failure: { (error) in
            
        }
    }
    
    
    
}
